package com.cuteboy.admin.service;

import com.cuteboy.dao.SysUserMapper;
import com.cuteboy.entity.SysRole;
import com.cuteboy.entity.SysUser;
import com.cuteboy.entity.SysUserRole;
import com.cuteboy.vo.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SysUserService {

    @Autowired
    @Qualifier("sysUserMapper")
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysRoleService sysRoleService;


    public List<SysUser> list(Integer currentPage, Integer pageSize){
        PageHelper.startPage(currentPage, pageSize);
        List<SysUser> sysUsers = sysUserMapper.selectAll();

        for(SysUser sysUser : sysUsers){
            packageVo(sysUser);
        }
        return sysUsers;
    }

    public void delete(String username){
        // 删除用户关联角色
        sysUserRoleService.deleteByUsername(username);
        // 删除用户
        sysUserMapper.deleteByPrimaryKey(username);
    }

    public SysUser save(SysUser entity){
        entity.setCreateTime(new Date());
        sysUserMapper.insertSelective(entity);
        return entity;
    }

    public SysUser update(SysUser entity){
        sysUserMapper.updateByPrimaryKey(entity);
        return entity;
    }

    public SysUser getEntity(String username){
        return sysUserMapper.selectByPrimaryKey(username);
    }

    public List<SysUser> selectByExample(Object o){
        return sysUserMapper.selectByExample(o);
    }

    public Integer countAll(){
        return sysUserMapper.countAll();
    }


    public void packageVo(SysUser sysUser){
        List<SysUserRole> sysUserRoles = sysUserRoleService.selectByUsername(sysUser.getUsername());

        List<Map> roles = new ArrayList<>();
        for (SysUserRole sysUserRole : sysUserRoles){
            SysRole sysRole = sysRoleService.selectByPrimaryKey(sysUserRole.getRoleId());

            Map roleMap = new HashMap();
            roleMap.put("roleId", sysUserRole.getRoleId());
            roleMap.put("name", sysRole.getName());
            roles.add(roleMap);
        }
        sysUser.setRoles(roles);
    }
}
